import axios from 'axios';
import type { AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import type { ApiError } from '../types/api';

// API配置
const API_CONFIG = {
  baseURL: import.meta.env?.VITE_API_BASE_URL || 'http://localhost:8080/api/v1',
  timeout: 30000,
  retryAttempts: 3,
  retryDelay: 1000,
};

// 创建Axios实例
export const apiClient: AxiosInstance = axios.create({
  baseURL: API_CONFIG.baseURL,
  timeout: API_CONFIG.timeout,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 当前连接ID存储
let currentConnectionId: string | null = null;

// 设置当前连接
export const setCurrentConnection = (connectionId: string): void => {
  currentConnectionId = connectionId;
};

// 获取当前连接
export const getCurrentConnection = (): string | null => {
  return currentConnectionId;
};

// 清除当前连接
export const clearCurrentConnection = (): void => {
  currentConnectionId = null;
};

// 认证Token存储
let authToken: string | null = null;

// 设置认证Token
export const setAuthToken = (token: string): void => {
  authToken = token;
  // 同时设置到axios默认头中
  apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;
};

// 获取认证Token
export const getAuthToken = (): string | null => {
  return authToken;
};

// 清除认证Token
export const clearAuthToken = (): void => {
  authToken = null;
  delete apiClient.defaults.headers.common['Authorization'];
};

// 构建查询字符串
export const buildQueryString = (params: Record<string, any>): string => {
  const query = new URLSearchParams();
  Object.keys(params).forEach(key => {
    if (params[key] !== undefined && params[key] !== null) {
      query.append(key, params[key].toString());
    }
  });
  return query.toString();
};

// 创建FormData
export const createFormData = (data: Record<string, any>): FormData => {
  const formData = new FormData();
  Object.keys(data).forEach(key => {
    if (data[key] !== undefined && data[key] !== null) {
      formData.append(key, data[key]);
    }
  });
  return formData;
};

// 统一API调用包装器
export const wrapApiCall = async <T>(promise: Promise<AxiosResponse<T>>): Promise<T> => {
  try {
    const response = await promise;
    return response.data;
  } catch (error) {
    // 统一错误处理
    const axiosError = error as AxiosError<ApiError>;
    throw new Error(
      axiosError.response?.data?.message || 
      axiosError.message || 
      'API调用失败'
    );
  }
};

// 请求拦截器
apiClient.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加当前连接ID到查询参数
    if (currentConnectionId) {
      const params = new URLSearchParams(config.params);
      params.set('connection', currentConnectionId);
      config.params = params;
    }
    
    // 可以在这里添加认证token等
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error: AxiosError<ApiError>) => {
    // 统一错误处理
    console.error('API Error:', error.response?.data?.message || error.message);
    return Promise.reject(error);
  }
);

// 重试机制
export const retryRequest = async <T>(
  request: () => Promise<T>,
  maxRetries: number = API_CONFIG.retryAttempts,
  delay: number = API_CONFIG.retryDelay
): Promise<T> => {
  let lastError: Error;
  
  for (let i = 0; i <= maxRetries; i++) {
    try {
      return await request();
    } catch (error) {
      lastError = error as Error;
      
      if (i === maxRetries) {
        throw lastError;
      }
      
      // 等待后重试
      await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i)));
    }
  }
  
  throw lastError!;
};

export default apiClient;